package com.wsc.service.impl;

import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.wsc.entity.Section;
import com.wsc.entity.Section;
import com.wsc.repository.SectionRepository;
import com.wsc.service.SectionService;

@Service
public class SectionServiceImpl implements SectionService {
	@Autowired
	private SectionRepository sr;

	@Override
	public Map<String, Object> getAll(Map<String, Object> params) {
		Specification<Section> spec = getSpec(params);
		Integer page = (Integer) params.get("page");
		Integer limit = (Integer) params.get("limit");
		Pageable pa = PageRequest.of(page, limit);
		// 调用查询方法
		Page<Section> res = sr.findAll(spec, pa);
		// data
		List<Section> data = res.getContent();
		// count
		long count = res.getTotalElements();
		if (data.size() > 0) {
			params.put("code", 0);
			params.put("data", data);
			params.put("count", count);
		} else {
			params.put("code", 1);
			params.put("msg", "数据异常");
		}
		return params;
	}

	private Specification<Section> getSpec(Map<String, Object> params) {
		return new Specification<Section>() {
			@Override
			public Predicate toPredicate(Root<Section> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				Predicate pre = cb.conjunction();
				List<Expression<Boolean>> sqllist = pre.getExpressions();
				if (!StringUtils.isEmpty(params.get("name"))) {
					sqllist.add(cb.like(root.get("name"), "%" + params.get("name") + "%"));
				}
				return pre;
			}
		};
	}

	@Override
	public Integer add(Section s) {
		try {
			sr.save(s);
			return 1;
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	@Override
	public Integer delete(Integer id) {
		try {
			sr.deleteById(id);
			return 1;
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	@Override
	public Integer update(Section s) {
		try {
			sr.save(s);
			return 1;
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

}
